/*******************************************************************************
 * BannerAdvertisersAction.java
 *
 * Created by Nishan
 * Last modified Date: Oct 24, 2008 4:52:35 PM by nishan
  * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 ******************************************************************************/
package com.printeverywhere.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.swing.ImageIcon;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.hibernate.HibernateException;

import com.opensymphony.xwork2.ActionContext;
import com.printeverywhere.delegator.BannerAccountsServiceDelegator;
import com.printeverywhere.delegator.BannerCampaignServiceDelegator;
import com.printeverywhere.delegator.BannerZonesServiceDelegator;
import com.printeverywhere.delegator.CategoryManagerServiceDelegator;
import com.printeverywhere.delegator.CommonFunctionDelegator;
import com.printeverywhere.dto.BannedUser;
import com.printeverywhere.dto.BannerAccount;
import com.printeverywhere.dto.BannerCampaigns;
import com.printeverywhere.dto.BannerClickLog;
import com.printeverywhere.dto.BannerDailyStatistics;
import com.printeverywhere.dto.BannerHourlyStatistics;
import com.printeverywhere.dto.BannerSettings;
import com.printeverywhere.dto.BannerZones;
import com.printeverywhere.dto.GeneralCategories;
import com.printeverywhere.dto.ListingOptions;
import com.printeverywhere.dto.User;
import com.printeverywhere.util.AdminConstants;
import com.printeverywhere.util.AttributeConstants;
import com.printeverywhere.util.CommonUtil;
import com.printeverywhere.util.DateUtil;
import com.printeverywhere.util.FileUtil;
import com.printeverywhere.util.ImageUtil;
import com.printeverywhere.util.SearchCriteria;
import com.printeverywhere.util.SessionUtil;

// TODO: Auto-generated Javadoc
/**
 * The Class BannerAdvertisersAction.
 */
public class BannerAdvertisersAction extends FrontBaseSupport implements
		ServletRequestAware {

	/**
	 * Instantiates a new banner advertisers action.
	 */
	public BannerAdvertisersAction() {
		super(true, false);
		setMyAccount(true);
	}

	/** Logger for this class. */
	private static final Logger logger = Logger
			.getLogger(BannerAdvertisersAction.class);

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/** The request. */
	private HttpServletRequest request;

	private User user;

	/** The banner account list. */
	private List<BannerAccount> bannerAccountList;

	/** The banner campaign list. */
	private List<BannerCampaigns> bannerCampaignList = new ArrayList<BannerCampaigns>();

	private List<BannerCampaigns> tmpBannerCampaignList;

	/** The banner zones list. */
	private List<BannerZones> bannerZonesList;

	private List<BannerSettings> bannerSettingsList;

	/** The banner account. */
	private BannerAccount bannerAccount;

	/** The banner campaigns. */
	private BannerCampaigns bannerCampaigns;

	/** The banner zone. */
	private BannerZones bannerZone;

	/** The str banner zones. */
	private String strBannerZones;

	private Integer campaignType;

	/** The banner settings. */
	private BannerSettings bannerSettings;

	/** The banner list. */
	private List<BannerCampaigns> bannerList;

	/** The statistic type. */
	private List<String> statisticType;

	/** The campaign id. */
	private int campaignId;

	/** The type. */
	private String type;

	/** The daily statistics list. */
	private List<BannerDailyStatistics> dailyStatisticsList;

	/** The hourly statistics list. */
	private List<BannerHourlyStatistics> hourlyStatisticsList;

	private ListingOptions listingOptions;

	/** The banners map. */
	private Map<Integer, BannerCampaigns> bannersMap;

	private Date today;

	private File upload;

	/** The content type. */
	private String contentType;

    /** The filename. */
    private String filename;

    private Integer bannerTypeId;

    private SearchCriteria searchCriteria = new SearchCriteria();

	/**
	 * Gets the hourly statistics list.
	 *
	 * @return the hourlyStatisticsList
	 */
	public List<BannerHourlyStatistics> getHourlyStatisticsList() {
		return hourlyStatisticsList;
	}

	/**
	 * Sets the hourly statistics list.
	 *
	 * @param hourlyStatisticsList the hourlyStatisticsList to set
	 */
	public void setHourlyStatisticsList(
			List<BannerHourlyStatistics> hourlyStatisticsList) {
		this.hourlyStatisticsList = hourlyStatisticsList;
	}

	/**
	 * Gets the daily statistics list.
	 *
	 * @return the dailyStatisticsList
	 */
	public List<BannerDailyStatistics> getDailyStatisticsList() {
		return dailyStatisticsList;
	}

	/**
	 * Sets the daily statistics list.
	 *
	 * @param dailyStatisticsList the dailyStatisticsList to set
	 */
	public void setDailyStatisticsList(
			List<BannerDailyStatistics> dailyStatisticsList) {
		this.dailyStatisticsList = dailyStatisticsList;
	}

	/**
	 * Gets the type.
	 *
	 * @return the type
	 */
	public String getType() {
		return type;
	}

	/**
	 * Sets the type.
	 *
	 * @param type the type to set
	 */
	public void setType(String type) {
		this.type = type;
	}

	/**
	 * Gets the campaign id.
	 *
	 * @return the campaignId
	 */
	public int getCampaignId() {
		return campaignId;
	}

	/**
	 * Sets the campaign id.
	 *
	 * @param campaignId the campaignId to set
	 */
	public void setCampaignId(int campaignId) {
		this.campaignId = campaignId;
	}

	/**
	 * Gets the banner settings.
	 *
	 * @return the bannerSettings
	 */
	public BannerSettings getBannerSettings() {
		return bannerSettings;
	}

	/**
	 * Sets the banner settings.
	 *
	 * @param bannerSettings the bannerSettings to set
	 */
	public void setBannerSettings(BannerSettings bannerSettings) {
		this.bannerSettings = bannerSettings;
	}

	/**
	 * Gets the str banner zones.
	 *
	 * @return the str banner zones
	 */
	public String getStrBannerZones() {
		return strBannerZones;
	}

	/**
	 * Sets the str banner zones.
	 *
	 * @param strBannerZones the new str banner zones
	 */
	public void setStrBannerZones(String strBannerZones) {
		this.strBannerZones = strBannerZones;
	}

	/**
	 * Gets the banner campaigns.
	 *
	 * @return the banner campaigns
	 */
	public BannerCampaigns getBannerCampaigns() {
		return bannerCampaigns;
	}

	/**
	 * Sets the banner campaigns.
	 *
	 * @param bannerCampaigns the new banner campaigns
	 */
	public void setBannerCampaigns(BannerCampaigns bannerCampaigns) {
		this.bannerCampaigns = bannerCampaigns;
	}

	/**
	 * Gets the banner account.
	 *
	 * @return the banner account
	 */
	public BannerAccount getBannerAccount() {
		return bannerAccount;
	}

	/**
	 * Sets the banner account.
	 *
	 * @param bannerAccount the new banner account
	 */
	public void setBannerAccount(BannerAccount bannerAccount) {
		this.bannerAccount = bannerAccount;
	}

	/**
	 * Gets the banner account list.
	 *
	 * @return the banner account list
	 */
	public List<BannerAccount> getBannerAccountList() {
		return bannerAccountList;
	}

	/**
	 * Sets the banner account list.
	 *
	 * @param bannerAccountList the new banner account list
	 */
	public void setBannerAccountList(List<BannerAccount> bannerAccountList) {
		this.bannerAccountList = bannerAccountList;
	}

	/**
	 * Gets the banner campaign list.
	 *
	 * @return the banner campaign list
	 */
	public List<BannerCampaigns> getBannerCampaignList() {
		return bannerCampaignList;
	}

	/**
	 * Sets the banner campaign list.
	 *
	 * @param bannerCampaignList the new banner campaign list
	 */
	public void setBannerCampaignList(List<BannerCampaigns> bannerCampaignList) {
		this.bannerCampaignList = bannerCampaignList;
	}

	/**
	 * Gets the banner zones list.
	 *
	 * @return the banner zones list
	 */
	public List<BannerZones> getBannerZonesList() {
		return bannerZonesList;
	}

	/**
	 * Sets the banner zones list.
	 *
	 * @param bannerZonesList the new banner zones list
	 */
	public void setBannerZonesList(List<BannerZones> bannerZonesList) {
		this.bannerZonesList = bannerZonesList;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.opensymphony.xwork2.ActionSupport#execute()
	 */
	public String execute() throws Exception {
		return SUCCESS;
	}

	/**
	 * Show add new account.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String showAddNewAccount() throws Exception {
		return SUCCESS;
	}

	/**
	 * Creates the banner account.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String createBannerAccount() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("createBannerAccount() - start"); //$NON-NLS-1$
		}
		try {
			BannerAccountsServiceDelegator.inserBannerAccount(bannerAccount);
		} catch (HibernateException e) {
			return INPUT;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("createBannerAccount() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	public String clickOnBanner() throws Exception {
		try {
			if(request.getParameter("adId") != null) {
				bannerCampaigns = (BannerCampaigns) CommonFunctionDelegator.getObjectById("id", Integer.parseInt(request.getParameter("adId")), BannerCampaigns.class);
				if(request.getHeader("Referer").indexOf("clickOnBanner") == -1) {
					BannerClickLog bannerClickLog = new BannerClickLog();
					bannerClickLog.setAction(AdminConstants.ONE_NUMBER);
					bannerClickLog.setAgent(request.getHeader("User-Agent"));
					bannerClickLog.setBannerCampaigns(bannerCampaigns);
					bannerClickLog.setRefer(request.getHeader("Referer"));
					bannerClickLog.setRemote(request.getRemoteAddr());
					bannerClickLog.setTime(DateUtil.getTodaysDate().toString());
					CommonFunctionDelegator.generalInsertbyobj(bannerClickLog);

					bannerCampaigns.setClicks(bannerCampaigns.getClicks() + 1);
					CommonFunctionDelegator.generalUpdatebyobj(bannerCampaigns);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * Show add new campaign.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String showAddNewCampaign() throws Exception {
		try{
			if (logger.isDebugEnabled()) {
				logger.debug("showAddNewCampaign() - start"); //$NON-NLS-1$
			}
			if(request.getParameter(AdminConstants.ID)!= null){
				int id = Integer.parseInt(request.getParameter(AdminConstants.ID));
				bannerCampaigns = (BannerCampaigns) CommonFunctionDelegator.getObjectById(AdminConstants.ID, id, BannerCampaigns.class);
				if(bannerCampaigns.getGeneralCategories() != null){
					bannerCampaigns.setCategories(getGeneralCategoriesFromCategoryId(bannerCampaigns.getGeneralCategories().getCategoryId()));
				}
			}

			this.bannerAccountList = BannerAccountsServiceDelegator
					.getBannerAccounts();
			bannerSettingsList = (List<BannerSettings>) CommonFunctionDelegator.getAllfromtable(BannerSettings.class.getName());

			if (logger.isDebugEnabled()) {
				logger.debug("showAddNewCampaign() - end"); //$NON-NLS-1$
			}
		}catch (Exception e) {
			logger.error(e.getLocalizedMessage());
		}
		return SUCCESS;
	}

	public void getBannerData(){
		try{
			this.bannerAccountList = BannerAccountsServiceDelegator
			.getBannerAccounts();
			bannerSettingsList = (List<BannerSettings>) CommonFunctionDelegator.getAllfromtable(BannerSettings.class.getName());
		}catch (Exception e) {
			addActionError("Error in getting banner data.");
		}
	}

	/**
	 * Creates the campaign.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String createCampaign() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("createCampaign() - start"); //$NON-NLS-1$
		}
		try{
			listingOptions = (ListingOptions) ActionContext.getContext().getApplication().get(AdminConstants.LISTING_OPTIONS);
			user = SessionUtil.getUser(request);
			/**/
			List<BannedUser> bannedUserList = new ArrayList<BannedUser>();
			bannedUserList = (List<BannedUser>) CommonFunctionDelegator.getAllfromtable(BannedUser.class.getName());
			if(bannedUserList.size() > 0){
				for (Iterator<BannedUser> iterator = bannedUserList.iterator(); iterator
						.hasNext();) {
					BannedUser bannedUser = (BannedUser) iterator.next();
					if(bannedUser.getUser().getId().intValue() ==  user.getId().intValue()){
						addActionError("You can not create campaign as you are blocked by admin.");
						return INPUT;
					}
				}
			}

			bannerCampaigns.setUser(user);

			/* Sets the value which banner format user selected.*/
			if(bannerTypeId != null){
				BannerSettings bannerSettings = (BannerSettings) CommonFunctionDelegator.getObjectById(AdminConstants.ID, bannerTypeId, BannerSettings.class);
				if(bannerSettings != null){
					bannerCampaigns.setBannerSettings(bannerSettings);
				}
			}
			/* Deciding whether you can add new campaign for the format you selected.*/
			if(bannerCampaigns.getBannerFormats().size() >= bannerCampaigns.getBannerSettings().getNoOfFormat()){
				addActionError("You can not define more campaign for this banner format.");
				return INPUT;
			}
			/* Banner campaign should be for future date. */
			if(bannerCampaigns.getStartDate() != null){
				if(bannerCampaigns.getStartDate().before(DateUtil.getTodaysDate())){
					addActionError("Please, select future date.");
					getBannerData();
					return INPUT;
				}
			}else{
				addActionError("Please, enter start date.");
				return INPUT;
			}
			/* If Campaign type selected it should not be null or zero. */
			if(campaignType.equals(1) && (bannerCampaigns.getMaxClicks().equals(0) || bannerCampaigns.getMaxClicks().equals(AdminConstants.NONE))){
				getBannerData();
				addActionError("Please, enter value for clicks other than zero..");
				return INPUT;
			}
			if(campaignType.equals(2) && (bannerCampaigns.getMaxViews().equals(0) || bannerCampaigns.getMaxViews().equals(AdminConstants.NONE))){
				getBannerData();
				addActionError("Please, enter value for views other than zero..");
				return INPUT;
			}
			if(campaignType.equals(3) && (bannerCampaigns.getMaxDays().equals(0) || bannerCampaigns.getMaxDays().equals(AdminConstants.NONE))){
				getBannerData();
				addActionError("Please, enter value for days other than zero..");
				return INPUT;
			}
			/* Set the general categories for selected category.*/
			if(request.getParameter(AdminConstants.CATEGORYID) != null){
				GeneralCategories generalCategories = CategoryManagerServiceDelegator.get(Integer.parseInt(request.getParameter(AdminConstants.CATEGORYID)));
				bannerCampaigns.setGeneralCategories(generalCategories);
			}
			/* Set the value for the per day campaign type. */
			if(bannerCampaigns.getDays() != null){
				Date date = DateUtil.addDate(bannerCampaigns.getStartDate(), Calendar.DATE, bannerCampaigns.getDays());
				bannerCampaigns.setEndDate(date);
			}
			/* If new image is uploaded following needs to be done. */
			if (this.upload != null) {
				try {
					/*Image type should be from the selected one.*/
					if (!CommonUtil.isImage(FileUtils
							.readFileToByteArray(upload))) {
						addActionError(getText("struts.messages.error.uploading"));
						return INPUT;
					}
					/*if (FileUtils.readFileToByteArray(upload).length > listingOptions
							.getMaximumUploadFileSize()) {
						addActionError("Image is larger than size specified by admin.");
						return INPUT;
					}*/
					/* Height and width given by the user should be <= decided by the admin for the selected format.*/
					if(bannerCampaigns.getHeight() > bannerCampaigns.getBannerSettings().getMaxHieght() || bannerCampaigns.getWidth() > bannerCampaigns.getBannerSettings().getMaxWidth()){
						addActionError("Given image height and width is larger than the size decided by admin for format: "+ bannerCampaigns.getBannerSettings().getFormatName());
						return INPUT;
					}else {
						String imgExtension = FileUtil.getFileExtension(filename);
						bannerCampaigns.setImage(ImageUtil.resizeImageAsJPG(FileUtils.readFileToByteArray(upload), bannerCampaigns.getWidth(), bannerCampaigns.getHeight(), imgExtension));
					}

				} catch (Exception e) {
					addActionError(getText("struts.messages.error.uploading"));
					return INPUT;
				}
			}
			/* For the campaign being updated. */
			if((request.getParameter(AdminConstants.ID) != null)&&(!request.getParameter(AdminConstants.ID).equals(AdminConstants.NONE))){
				int id = Integer.parseInt(request.getParameter(AdminConstants.ID));
				bannerCampaigns.setUser(user);
//				bannerCampaigns.setImage(FileUtils.readFileToByteArray(upload));
				if(this.upload != null) {}
				else{
					BannerCampaigns tempBannerCampaigns = (BannerCampaigns) CommonFunctionDelegator.getObjectById(AdminConstants.ID, id, BannerCampaigns.class);
					bannerCampaigns.setImage(tempBannerCampaigns.getImage());
				}
				CommonFunctionDelegator.generalUpdatebyobj(bannerCampaigns);
			}else{
				/* Setting the banner campaign pending initially.*/
				bannerCampaigns.setStatus(AdminConstants.ONE_NUMBER);
				BannerCampaignServiceDelegator.inserBannerCampaigns(bannerCampaigns);
			}
		}catch (Exception e) {
			getBannerData();
			addActionError("Campaign not added/updated.".intern());
			return INPUT;
		}finally {
			getBannerData();
			if(super.hasErrors()){
				if((request.getParameter(AdminConstants.ID) != null)&&(!request.getParameter(AdminConstants.ID).equals(AdminConstants.NONE))){
					int id = Integer.parseInt(request.getParameter(AdminConstants.ID));
					 bannerCampaigns = (BannerCampaigns) CommonFunctionDelegator.getObjectById(AdminConstants.ID, id, BannerCampaigns.class);
				}
			}
		}
		if (logger.isDebugEnabled()) {
			logger.debug("createCampaign() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	public boolean validateImage(byte[] image, BannerSettings bannerSettings){
		ImageIcon imageIcon = new ImageIcon(image);
		int width = imageIcon.getIconWidth();
		int height = imageIcon.getIconHeight();
		if(height > bannerSettings.getMaxHieght() || width > bannerSettings.getMaxWidth()){
			return false;
		}
		return true;
	}
	@Override
	public void validate() {
		super.validate();
		if(super.hasFieldErrors()){
			getBannerData();
		}
	}
	public String modifyCampaign(){
		try {
			if((request.getParameter(AdminConstants.ID) != null)&& (request.getParameter("param") != null)){
				int id = Integer.parseInt(request.getParameter(AdminConstants.ID));
				bannerCampaigns = (BannerCampaigns) CommonFunctionDelegator.getObjectById(AdminConstants.ID, id, BannerCampaigns.class);
				bannerCampaigns.setId(id);
				if(request.getParameter("param").equals("delete")){
					CommonFunctionDelegator.GeneralDelete(bannerCampaigns);
					return SUCCESS;
				}
				if(request.getParameter("param").equals("resubmit")){
					bannerCampaigns.setStatus(AttributeConstants.CAMPAIGNSTATUS_ACTIVE);
				}
				if(request.getParameter("param").equals("suspend")){
					bannerCampaigns.setStatus(AttributeConstants.CAMPAIGNSTATUS_SUSPENDED);
				}
				CommonFunctionDelegator.generalUpdatebyobj(bannerCampaigns);
			}
		} catch (Exception e) {
			return INPUT;
		}
		return SUCCESS;
	}

	/**
	 * Show manage accounts.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String showManageAccounts() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("showManageAccounts() - start"); //$NON-NLS-1$
		}
		try{
			user = SessionUtil.getUser(request);
			searchCriteria.removeAllAttribute();
			searchCriteria.setAttribute(AdminConstants.USER, user);
			this.tmpBannerCampaignList = (List<BannerCampaigns>) CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, BannerCampaigns.class);
			if(tmpBannerCampaignList.size() > 0){
				for (Iterator iterator = tmpBannerCampaignList.iterator(); iterator.hasNext();) {
					BannerCampaigns type = (BannerCampaigns) iterator.next();
					if(type.getGeneralCategories() != null){
						type.setCategories(getGeneralCategoriesFromCategoryId(type.getGeneralCategories().getCategoryId()));
					}
					bannerCampaignList.add(type);
				}
			}
			today = DateUtil.getTodaysDate();
		}catch (Exception e) {
			logger.error(e.getMessage());
			addActionError("Problem getting banner campaigns.");
			return INPUT;
		}



		/*this.bannerAccountList = BannerAccountsServiceDelegator
				.getBannerAccounts();
		int totalBannerAccount = this.bannerAccountList.size();
		for (int index = 0; index < totalBannerAccount; index++) {
			BannerAccount bannerAccount = this.bannerAccountList.get(index);
			bannerAccount.setTotalCampaigns(BannerCampaignServiceDelegator
					.countBannerCampaigns(bannerAccount.getId()));
			this.bannerAccountList.set(index, bannerAccount);
		}*/

		if (logger.isDebugEnabled()) {
			logger.debug("showManageAccounts() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	public String advertiserReport(){
		try {
			user = SessionUtil.getUser(request);

			searchCriteria.removeAllAttribute();
			searchCriteria.setAttribute(AdminConstants.USER, user);
			if(bannerCampaignList.size() > 0){
				bannerCampaignList.clear();
			}
			bannerCampaignList = (List<BannerCampaigns>) CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, BannerCampaigns.class);
		} catch (Exception e) {
			addActionError("Error in retriving advertiser Report.".intern());
			return INPUT;
		}
		return SUCCESS;
	}

	public String modifyBannerCampaign(){
		try {
			if(request.getParameter(AdminConstants.ID) != null){
				int id = Integer.parseInt(request.getParameter(AdminConstants.ID));
				bannerCampaigns = (BannerCampaigns) CommonFunctionDelegator.getObjectById(AdminConstants.ID, id, BannerCampaigns.class);
				if(bannerCampaigns != null){
					if((request.getParameter("param") != null) && (request.getParameter("param").equals("delete"))){
						CommonFunctionDelegator.GeneralDelete(bannerCampaigns);
					} else if((request.getParameter("param") != null) && (request.getParameter("param").equals("active"))){
						bannerCampaigns.setActive(true);
						CommonFunctionDelegator.generalUpdatebyobj(bannerCampaigns);
					}else if((request.getParameter("param") != null) && (request.getParameter("param").equals("inactive"))){
						bannerCampaigns.setActive(false);
						CommonFunctionDelegator.generalUpdatebyobj(bannerCampaigns);
					}
				}
			}
		} catch (Exception e) {
			return INPUT;
		}
		return SUCCESS;
	}

	public String advertiseConfig(){
		try{
			if(request.getParameter(AdminConstants.ID) != null){
				int id = Integer.parseInt(request.getParameter(AdminConstants.ID));
				bannerCampaigns = (BannerCampaigns) CommonFunctionDelegator.getObjectById(AdminConstants.ID, id, BannerCampaigns.class);
				this.bannerZonesList = BannerZonesServiceDelegator.getBannerZones();
			}
		}catch (Exception e) {
			return INPUT;
		}
		return SUCCESS;
	}
	/**
	 * Show manage campaigns.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String showManageCampaigns() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("showManageCampaigns() - start"); //$NON-NLS-1$
		}
		try{
			this.bannerCampaignList = BannerCampaignServiceDelegator
					.getBannerCampaigns();
			today = DateUtil.getTodaysDate();
		}catch (Exception e) {
			return INPUT;
		}
		if (logger.isDebugEnabled()) {
			logger.debug("showManageCampaigns() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Show banner settings.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String showBannerSettings() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("showBannerSettings() - start"); //$NON-NLS-1$
		}
		try{
			bannerSettings = BannerCampaignServiceDelegator.getBannerSettings();
		}catch (Exception e) {
			return INPUT;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("showBannerSettings() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Edits the banner settings.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String editBannerSettings() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("showBannerSettings() - start"); //$NON-NLS-1$
		}
		try{
			BannerCampaignServiceDelegator.editBannerSetting(bannerSettings);
		}catch (Exception e) {
			return INPUT;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("showBannerSettings() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Show banner statistics.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String showBannerStatistics() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("showBannerStatistics() - start"); //$NON-NLS-1$
		}

		populateBannerSearchList();

		if (logger.isDebugEnabled()) {
			logger.debug("showBannerStatistics() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Gets the banner statistics.
	 *
	 * @return the banner statistics
	 *
	 * @throws Exception the exception
	 */
	public String getBannerStatistics() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("getBannerStatistics() - start"); //$NON-NLS-1$
		}
		populateBannerSearchList();
		SearchCriteria searchCriteria = new SearchCriteria();
		if (campaignId == 0) {
			addActionError("Please Select Campaign ");
			return INPUT;
		} else if (type.equalsIgnoreCase("daily")) {
			searchCriteria.setAttribute("bannerCampaigns.id", campaignId);
			dailyStatisticsList = BannerCampaignServiceDelegator.getDailyStatisticsList(searchCriteria);

		} else if (type.equalsIgnoreCase("hourly")) {
			searchCriteria.setAttribute("bannerCampaigns.id", campaignId);
			hourlyStatisticsList = BannerCampaignServiceDelegator.getHourlyStatisticsList(searchCriteria);
		}

		if (logger.isDebugEnabled()) {
			logger.debug("getBannerStatistics() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Populate banner search list.
	 */
	public void populateBannerSearchList() {
		if (logger.isDebugEnabled()) {
			logger.debug("populateBannerSearchList() - start"); //$NON-NLS-1$
		}
		this.bannersMap = new HashMap<Integer, BannerCampaigns>();
		this.bannerList = BannerCampaignServiceDelegator.getBannerCampaigns();

		for (BannerCampaigns bannersCampaigns : bannerList) {
			this.bannersMap.put(bannersCampaigns.getId(), bannersCampaigns);
		}

		statisticType = new ArrayList<String>();
		statisticType.add("DAILY");
		statisticType.add("HOURLY");
		statisticType.add("WEEKLY");
		statisticType.add("MONTHLY");
		statisticType.add("YEARLY");
		if (logger.isDebugEnabled()) {
			logger.debug("populateBannerSearchList() - end"); //$NON-NLS-1$
		}
	}

	/**
	 * Show campaigns.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String showCampaigns() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("showCampaigns() - start"); //$NON-NLS-1$
		}
		populateBannerSearchList();

		if (logger.isDebugEnabled()) {
			logger.debug("showCampaigns() - end"); //$NON-NLS-1$
		}
		return SUCCESS;

	}

	/**
	 * Show manage zones.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String showManageZones() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("showManageZones() - start"); //$NON-NLS-1$
		}

		this.bannerZonesList = BannerZonesServiceDelegator.getBannerZones();

		if (logger.isDebugEnabled()) {
			logger.debug("showManageZones() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Show zones configuration.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String showZonesConfiguration() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("showZonesConfiguration() - start"); //$NON-NLS-1$
		}

		if (this.request.getParameter("id") != null) {
			this.bannerZone = BannerZonesServiceDelegator
					.getBannerZoneById(Integer.parseInt(this.request
							.getParameter("id")));
			this.bannerZonesList = BannerZonesServiceDelegator.getBannerZones();
			this.bannerCampaignList = BannerCampaignServiceDelegator
					.getBannerCampaigns();
		}

		if (logger.isDebugEnabled()) {
			logger.debug("showZonesConfiguration() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Update zone configuration.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String updateZoneConfiguration() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("updateZoneConfiguration() - start"); //$NON-NLS-1$
		}

		BannerZonesServiceDelegator.updateBannerZones(this.bannerZone);

		if (logger.isDebugEnabled()) {
			logger.debug("updateZoneConfiguration() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Creates the zones.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String createZones() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("createZones() - start"); //$NON-NLS-1$
		}

		String[] zones = this.strBannerZones.split(",");

		for (String zone : zones) {
			if (zone.trim().length() > 1) {
				BannerZones bannerZones = new BannerZones();
				bannerZones.setZone(zone);
				BannerZonesServiceDelegator.inserBannerZones(bannerZones);
			}
		}

		if (logger.isDebugEnabled()) {
			logger.debug("createZones() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Delete zones.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String deleteZones() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("deleteZones() - start"); //$NON-NLS-1$
		}

		try {
			if (this.request.getParameter("id") != null) {
				this.bannerZone = BannerZonesServiceDelegator
						.getBannerZoneById(Integer.parseInt(this.request
								.getParameter("id")));
				BannerZonesServiceDelegator.deleteBannerZones(this.bannerZone);
			}

			if (logger.isDebugEnabled()) {
				logger.debug("deleteZones() - end"); //$NON-NLS-1$
			}
			return SUCCESS;
		} catch (Exception e) {
			logger.error("deleteZones()", e); //$NON-NLS-1$

			addActionMessage("Can't delete this record...");
			this.bannerZonesList = BannerZonesServiceDelegator.getBannerZones();
		}

		if (logger.isDebugEnabled()) {
			logger.debug("deleteZones() - end"); //$NON-NLS-1$
		}
		return INPUT;
	}

	public String[] getGeneralCategoriesFromCategoryId(int categoryid){
		List<String> tmpCategories = new ArrayList<String>();
		String[] categories;
    	GeneralCategories generalCategories = CategoryManagerServiceDelegator.get(categoryid);
    	while (generalCategories.getCategoryId() != generalCategories.getGeneralCategories().getCategoryId()) {
    		tmpCategories.add(generalCategories.getCategoryName());
			generalCategories = generalCategories.getGeneralCategories();
		}
    	tmpCategories.add(generalCategories.getCategoryName());

    	Collections.reverse(tmpCategories);
    	categories = tmpCategories.toArray(new String[0]);

		return categories;
	}

	/**
	 * Gets the banner zone.
	 *
	 * @return the banner zone
	 */
	public BannerZones getBannerZone() {
		return bannerZone;
	}

	/**
	 * Sets the banner zone.
	 *
	 * @param bannerZone the new banner zone
	 */
	public void setBannerZone(BannerZones bannerZone) {
		this.bannerZone = bannerZone;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.apache.struts2.interceptor.ServletRequestAware#setServletRequest(javax.servlet.http.HttpServletRequest)
	 */
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	/**
	 * Gets the statistic type.
	 *
	 * @return the statisticType
	 */
	public List<String> getStatisticType() {
		return statisticType;
	}

	/**
	 * Sets the statistic type.
	 *
	 * @param statisticType the statisticType to set
	 */
	public void setStatisticType(List<String> statisticType) {
		this.statisticType = statisticType;
	}

	/**
	 * @return the bannerList
	 */
	public List<BannerCampaigns> getBannerList() {
		return bannerList;
	}

	/**
	 * @param bannerList the bannerList to set
	 */
	public void setBannerList(List<BannerCampaigns> bannerList) {
		this.bannerList = bannerList;
	}

	/**
	 * @return the bannersMap
	 */
	public Map<Integer, BannerCampaigns> getBannersMap() {
		return bannersMap;
	}

	/**
	 * @param bannersMap the bannersMap to set
	 */
	public void setBannersMap(Map<Integer, BannerCampaigns> bannersMap) {
		this.bannersMap = bannersMap;
	}

	public Date getToday() {
		return today;
	}

	public void setToday(Date today) {
		this.today = today;
	}


	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	/**
	 * Sets the upload content type.
	 *
	 * @param contentType the new upload content type
	 */
	public void setUploadContentType(String contentType) {
        this.contentType = contentType;
     }

	/**
	 * Sets the upload file name.
	 *
	 * @param filename the new upload file name
	 */
	public void setUploadFileName(String filename) {
        this.filename = filename;
     }

	public String  getUploadContentType() {
	       return contentType;
	}

	public String getUploadFilename() {
		return filename;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}
	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public List<BannerSettings> getBannerSettingsList() {
		return bannerSettingsList;
	}

	public void setBannerSettingsList(List<BannerSettings> bannerSettingsList) {
		this.bannerSettingsList = bannerSettingsList;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Integer getBannerTypeId() {
		return bannerTypeId;
	}

	public void setBannerTypeId(Integer bannerTypeId) {
		this.bannerTypeId = bannerTypeId;
	}

	public ListingOptions getListingOptions() {
		return listingOptions;
	}

	public void setListingOptions(ListingOptions listingOptions) {
		this.listingOptions = listingOptions;
	}

	public Integer getCampaignType() {
		return campaignType;
	}

	public void setCampaignType(Integer campaignType) {
		this.campaignType = campaignType;
	}
}